package com.lxr0860.lxr0860production_test.itemactivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;


import com.lxr0860.lxr0860production_test.R;
import com.lxr0860.lxr0860production_test.utils.AudioRecorderUtils;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.view.HorizontalProgressBar;

import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.text.SimpleDateFormat;


public class AudioActivity extends Activity {
    private TextView mTvTitle,mTvTip, mTvTime;
    private HorizontalProgressBar mProgress;
    private Button mBtnStart;
    private MediaPlayer mMediaPlayer;
    private AssetManager mAssetManager;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Contants.DIALOG_POSITIVE:
                    Intent mIntent=new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putBoolean("result",true);
                    mIntent.putExtras(bundle);
                    AudioActivity.this.setResult(Contants.TEST_ITEM_AUDIO,mIntent);
                    finish();
                    break;
                case Contants.DIALOG_NEGATIVE:
                    break;
            }
        }
    };
    private long mMusicTime, mMaxTime;

    private Runnable musicRunnable = new Runnable() {
        @Override
        public void run() {
            mProgress.setProgress((int) mMusicTime);
            mTvTime.setText(formatTime(mMusicTime));
            mMusicTime += AudioRecorderUtils.SPACE;
            handler.postDelayed(this, AudioRecorderUtils.SPACE);
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_phone);
        initView();
        initData();
        initEvent();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realseMusic();
    }

    private void initView() {
        mTvTitle= (TextView) findViewById(R.id.tv_audio_title);
        mBtnStart = (Button) findViewById(R.id.btn_phone_start);
        mTvTime = (TextView) findViewById(R.id.tv_phone_test_time);
        mTvTip = (TextView) findViewById(R.id.tv_phone_tip);
        mProgress =  findViewById(R.id.pb_phone_test);
    }

    private void initData() {
        mTvTitle.setText(Contants.itemTitles[Contants.TEST_ITEM_AUDIO]);
        mAssetManager = getAssets();
    }

    private void initEvent() {
        mBtnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBtnStart.setEnabled(false);
                prepareMusic();
            }
        });
    }

    private void prepareMusic() {
        AudioManager audiomanage = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audiomanage.setMode(AudioManager.MODE_NORMAL);
        audiomanage.setStreamVolume(AudioManager.STREAM_MUSIC, 30, AudioManager.FLAG_SHOW_UI);
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
        }else {
            mMediaPlayer.reset();
        }
        try {
            AssetFileDescriptor fileDescriptor = mAssetManager.openFd("phone.wav");
            mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
                    fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            mMediaPlayer.prepare();
            mMusicTime = 0;
            mMaxTime = mMediaPlayer.getDuration();
            mProgress.setMax((int) mMaxTime);
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.stop();
                    handler.removeCallbacks(musicRunnable);
                    mProgress.setProgress(0);
                    mTvTime.setText(formatTime(0));
                    mTvTip.setText("测试完毕");
                    Contants.showDailog(AudioActivity.this,
                            "测试完毕，喇叭是否正常",handler, Gravity.TOP);
                    mBtnStart.setEnabled(true);
                }
            });
            startMusic();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void startMusic() {
        mTvTip.setText("正在进行喇叭测试");
        mTvTime.setText("播放已开始");
        if (!mMediaPlayer.isPlaying()) {
            handler.post(musicRunnable);
            mMediaPlayer.start();
        }
    }

    private void pauseMusic() {
        mTvTime.setText("播放已暂停");
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            handler.removeCallbacks(musicRunnable);
        }
    }

    private void realseMusic() {
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer.release();
        }
    }

    private String formatTime(long time) {
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        String formatTime = formatter.format(time);
        return formatTime;
    }
}